import { PlusOutlined } from '@ant-design/icons';
import {
  ActionType,
  PageContainer,
  ProColumns,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Tag, Space, Modal, message } from 'antd';
import React, { useRef, useState } from 'react';

type Campsite = {
  id: number;
  name: string;
  address: string;
  province: string;
  city: string;
  owner: string;
  ownerId: number;
  createTime: string;
  status: 'published' | 'unpublished' | 'pending';
  price: number;
  rating: number;
  facilities: string[];
};

const statusMap = {
  published: { text: '已发布', color: 'green' },
  unpublished: { text: '未发布', color: 'orange' },
  pending: { text: '待审核', color: 'blue' },
};

const facilityOptions = [
  '停车场',
  'WiFi',
  '淋浴',
  '厕所',
  '烧烤',
  '帐篷出租',
  '餐饮',
  '户外活动',
  '游泳池',
];

const Campsites: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [selectedRows, setSelectedRows] = useState<Campsite[]>([]);

  // 模拟数据
  const mockCampsites: Campsite[] = Array.from({ length: 50 }).map((_, index) => ({
    id: index + 1,
    name: `快乐营地 ${index + 1}`,
    address: `某省某市某区某街道${index + 1}号`,
    province: ['北京', '上海', '广东', '浙江', '四川'][Math.floor(Math.random() * 5)],
    city: ['北京', '上海', '广州', '杭州', '成都'][Math.floor(Math.random() * 5)],
    owner: `商家${Math.floor(Math.random() * 100)}`,
    ownerId: Math.floor(Math.random() * 100),
    createTime: new Date(Date.now() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000).toISOString(),
    status: ['published', 'unpublished', 'pending'][Math.floor(Math.random() * 3)] as any,
    price: Math.floor(Math.random() * 500) + 100,
    rating: Math.floor(Math.random() * 50) / 10,
    facilities: Array.from({ length: Math.floor(Math.random() * 5) + 1 }).map(
      () => facilityOptions[Math.floor(Math.random() * facilityOptions.length)]
    ),
  }));

  // 模拟请求数据
  const fetchCampsites = async (params: any) => {
    const { current, pageSize, name, status, province, city } = params;
    
    let filteredData = [...mockCampsites];
    
    if (name) {
      filteredData = filteredData.filter(item => item.name.includes(name));
    }
    
    if (status) {
      filteredData = filteredData.filter(item => item.status === status);
    }
    
    if (province) {
      filteredData = filteredData.filter(item => item.province === province);
    }
    
    if (city) {
      filteredData = filteredData.filter(item => item.city === city);
    }
    
    const startIndex = (current - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const data = filteredData.slice(startIndex, endIndex);
    
    return {
      data,
      success: true,
      total: filteredData.length,
    };
  };

  const handlePublish = (ids: number[], isPublish: boolean) => {
    Modal.confirm({
      title: `确定要${isPublish ? '发布' : '取消发布'}选中的营地吗？`,
      content: '此操作将改变营地的发布状态',
      onOk: () => {
        message.success(`已${isPublish ? '发布' : '取消发布'}选中的营地`);
        actionRef.current?.reload();
      },
    });
  };

  const handleDelete = (ids: number[]) => {
    Modal.confirm({
      title: '确定要删除选中的营地吗？',
      content: '此操作不可恢复',
      onOk: () => {
        message.success('已删除选中的营地');
        actionRef.current?.reload();
      },
    });
  };

  const columns: ProColumns<Campsite>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      search: false,
    },
    {
      title: '营地名称',
      dataIndex: 'name',
    },
    {
      title: '省份',
      dataIndex: 'province',
      valueEnum: {
        北京: { text: '北京' },
        上海: { text: '上海' },
        广东: { text: '广东' },
        浙江: { text: '浙江' },
        四川: { text: '四川' },
      },
    },
    {
      title: '城市',
      dataIndex: 'city',
      valueEnum: {
        北京: { text: '北京' },
        上海: { text: '上海' },
        广州: { text: '广州' },
        杭州: { text: '杭州' },
        成都: { text: '成都' },
      },
    },
    {
      title: '商家',
      dataIndex: 'owner',
      search: false,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      search: false,
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        published: { text: '已发布', status: 'Success' },
        unpublished: { text: '未发布', status: 'Warning' },
        pending: { text: '待审核', status: 'Processing' },
      },
    },
    {
      title: '价格/晚',
      dataIndex: 'price',
      search: false,
      render: (_, record) => `¥${record.price}`,
    },
    {
      title: '评分',
      dataIndex: 'rating',
      search: false,
    },
    {
      title: '设施',
      dataIndex: 'facilities',
      search: false,
      render: (_, record) => (
        <Space>
          {record.facilities.map(facility => (
            <Tag key={facility}>{facility}</Tag>
          ))}
        </Space>
      ),
    },
    {
      title: '操作',
      valueType: 'option',
      render: (_, record) => [
        <a key="edit" onClick={() => message.info(`编辑营地 ${record.id}`)}>
          编辑
        </a>,
        <a
          key="publish"
          onClick={() => handlePublish([record.id], record.status !== 'published')}
        >
          {record.status === 'published' ? '取消发布' : '发布'}
        </a>,
        <a key="delete" onClick={() => handleDelete([record.id])}>
          删除
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<Campsite>
        headerTitle="营地列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            key="create"
            type="primary"
            onClick={() => message.info('新建营地')}
            icon={<PlusOutlined />}
          >
            新建
          </Button>,
        ]}
        request={fetchCampsites}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
        tableAlertRender={({ selectedRowKeys, onCleanSelected }) => (
          <Space>
            <span>已选 {selectedRowKeys.length} 项</span>
            <a onClick={onCleanSelected}>取消选择</a>
          </Space>
        )}
        tableAlertOptionRender={() => (
          <Space>
            <Button
              onClick={() => handlePublish(
                selectedRows.map(row => row.id),
                true
              )}
            >
              批量发布
            </Button>
            <Button
              onClick={() => handlePublish(
                selectedRows.map(row => row.id),
                false
              )}
            >
              批量取消发布
            </Button>
            <Button
              danger
              onClick={() => handleDelete(selectedRows.map(row => row.id))}
            >
              批量删除
            </Button>
          </Space>
        )}
      />
    </PageContainer>
  );
};

export default Campsites; 